﻿using System.Collections.Generic;
using System.Xml;

namespace Jayden.Dll.Sc2.Descriptions
{
	public class CastActionDescription: BuildActionDescription
	{
		private double m_RequiredEnergy = 0.0;

		protected CastActionDescription(EntityDescription entity, EntityDescription build, string id, double energy)
			: base(entity, build, id)
		{
			m_RequiredEnergy = energy;
		}
		public CastActionDescription(EntityDescription entity, XmlNode node, string format = "{0}Cast{1}", string nameFormat = "{0} cast {1}")
			: base(entity, node, format, nameFormat)
		{
				LoadXml(node);
		}

		protected void LoadXml(XmlNode node)
		{
			m_RequiredEnergy = double.Parse(node.Attributes["energy"].Value);
		}

		public double RequiredEnergy { get { return m_RequiredEnergy; } }

		public override bool IsExecutable(GameState state)
		{
			GameState.EntityState entityState = state[Entity];
			if (entityState == null || entityState.Energy == null || entityState.Energy.Count == 0)
				return false;
			// check for input
			foreach (KeyValuePair<EntityDescription, int> pair in Build.InputDictionary)
			{
				entityState = state[pair.Key];
				if (entityState == null || entityState.Idle < pair.Value)
					return false;
			}
			foreach(double energy in entityState.Energy)
				if(energy >= m_RequiredEnergy)
					return base.IsExecutable(state);
			return false;
		}

		public override void Execute(GameState state)
		{
			GameState.EntityState entityState = state[Entity];
			bool casted = false;
			for (int c = 0; c < entityState.Energy.Count; c++)
			{
				double energy = entityState.Energy[c];
				if (energy >= m_RequiredEnergy)
				{
					entityState.Energy[c] = energy - m_RequiredEnergy;
					casted = true;
					break;
				}
			}
			if (casted)
				Cast(state);
		}

		protected virtual void Cast(GameState state)
		{
			base.Execute(state);
		}
	}
}
